package io.gitee.minelx.example.geohash;

import java.math.BigDecimal;

import static java.util.stream.Collectors.joining;

public class GeoHash {

    public static final Range LATITUDE_RANGE = Range.of(new BigDecimal(-90), new BigDecimal(90));
    public static final Range LONGITUDE_RANGE = Range.of(new BigDecimal(-180), new BigDecimal(180));

    public static String encode(double latitude, double longitude) {
        BigDecimal latitudeDecimal = new BigDecimal(latitude);
        BigDecimal longitudeDecimal = new BigDecimal(longitude);

        return encode(latitudeDecimal, longitudeDecimal);
    }

    static String encode(BigDecimal latitude, BigDecimal longitude) {
        Bits latitudeBits = Bits.of(LATITUDE_RANGE.determines(latitude, 22));
        Bits longitudeBits = Bits.of(LONGITUDE_RANGE.determines(longitude, 23));

        return longitudeBits.stack(latitudeBits)
                .partition(5)
                .map(Bits::reverse).map(Bits::decimal)
                .map(Base32::forward).map(String::valueOf)
                .collect(joining());
    }
}
